<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 管理后台</title>
    <link th:href="@{/admin/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/admin/css/bootstrap-icons.css}" rel="stylesheet">
    <link th:href="@{/admin/css/admin.css}" rel="stylesheet">
    <style>
        .search-filters {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .status-badge {
            font-size: 0.75rem;
        }
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" th:href="@{/admin}">
                <i class="bi bi-gear-fill me-2"></i>口语练习管理后台
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" th:href="@{/}" target="_blank">
                    <i class="bi bi-box-arrow-up-right me-1"></i>前台页面
                </a>
                <form th:action="@{/api/v1/auth/logout}" method="post" class="d-inline">
                    <button type="submit" class="btn btn-outline-light btn-sm">
                        <i class="bi bi-box-arrow-right me-1"></i>退出登录
                    </button>
                </form>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 bg-light sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav nav-pills flex-column">
                        <li class="nav-item">
                            <a th:href="@{/admin}" class="nav-link">
                                <i class="bi bi-house-door me-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/users}" class="nav-link active">
                                <i class="bi bi-people me-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/exam-papers}" class="nav-link">
                                <i class="bi bi-file-text me-2"></i>试卷管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/classes}" class="nav-link">
                                <i class="bi bi-building me-2"></i>班级管理
                            </a>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- 主内容 -->
            <main class="col-md-10 ms-sm-auto px-md-4">
                <!-- 页面标题 -->
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="bi bi-people me-2"></i>用户管理
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="refreshUsers()">
                            <i class="bi bi-arrow-clockwise me-1"></i>刷新数据
                        </button>
                    </div>
                </div>

                <!-- 消息提示区域 -->
                <div id="messageArea"></div>

                <!-- 统计卡片 -->
                <div class="row mb-4">
                    <div class="col-md-3 mb-3">
                        <div class="card border-info">
                            <div class="card-header bg-info text-white">
                                <i class="bi bi-people me-2"></i>总用户数
                            </div>
                            <div class="card-body">
                                <h4 class="card-title text-info" id="totalUsersCount" th:text="${allUsers != null ? allUsers.size() : 0}">0</h4>
                                <p class="card-text text-muted">系统中所有用户</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card border-warning">
                            <div class="card-header bg-warning text-dark">
                                <i class="bi bi-hourglass me-2"></i>待审核
                            </div>
                            <div class="card-body">
                                <h4 class="card-title text-warning" id="pendingUsersCount">0</h4>
                                <p class="card-text text-muted">需要审核的用户</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card border-success">
                            <div class="card-header bg-success text-white">
                                <i class="bi bi-check-circle me-2"></i>已批准
                            </div>
                            <div class="card-body">
                                <h4 class="card-title text-success" id="approvedUsersCount">0</h4>
                                <p class="card-text text-muted">已通过审核的用户</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card border-danger">
                            <div class="card-header bg-danger text-white">
                                <i class="bi bi-x-circle me-2"></i>已拒绝
                            </div>
                            <div class="card-body">
                                <h4 class="card-title text-danger" id="rejectedUsersCount">0</h4>
                                <p class="card-text text-muted">审核被拒绝的用户</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 搜索和筛选 -->
                <div class="search-filters">
                    <div class="row">
                        <div class="col-md-4">
                            <label class="form-label">搜索用户</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchInput" placeholder="输入真实姓名搜索...">
                                <button class="btn btn-outline-secondary" type="button" onclick="searchUsers()">
                                    <i class="bi bi-search"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">状态筛选</label>
                            <select class="form-select" id="statusFilter" onchange="filterUsers()">
                                <option value="">所有状态</option>
                                <option value="PENDING">待审核</option>
                                <option value="APPROVED">已批准</option>
                                <option value="REJECTED">已拒绝</option>
                                <option value="INCOMPLETE">信息不完整</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">用户类型</label>
                            <select class="form-select" id="userTypeFilter" onchange="filterUsers()">
                                <option value="">所有类型</option>
                                <option value="STUDENT">学生</option>
                                <option value="TEACHER">教师</option>
                                <option value="ADMIN">管理员</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="button" class="btn btn-secondary w-100" onclick="clearFilters()">
                                <i class="bi bi-x-lg me-1"></i>清除筛选
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 用户列表 -->
                <div class="table-container">
                    <div id="loadingIndicator" class="text-center p-4" style="display: none;">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">加载用户数据中...</p>
                    </div>
                    
                    <div id="usersTableContainer">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>姓名</th>
                                        <th>昵称</th>
                                        <th>类型</th>
                                        <th>状态</th>
                                        <th>性别</th>
                                        <th>班级ID</th>
                                        <th>注册时间</th>
                                        <th>最后登录</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="usersTableBody">
                                    <!-- 用户数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div id="emptyState" class="empty-state" style="display: none;">
                        <i class="bi bi-people display-1"></i>
                        <h4 class="mt-3">没有找到匹配的用户</h4>
                        <p>尝试调整搜索条件或筛选选项</p>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 确认操作模态框 -->
    <div class="modal fade" id="confirmModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">确认操作</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="modalBody">
                    确认要执行此操作吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn" id="confirmBtn" onclick="executeAction()">确认</button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/admin/js/bootstrap.bundle.min.js}"></script>
    <script>
        let allUsers = [];
        let filteredUsers = [];
        let pendingAction = null;
        let pendingUserId = null;
        let pendingUserName = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadUsers();
            
            // 搜索框实时搜索
            const searchInput = document.getElementById('searchInput');
            let searchTimeout;
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    filterUsers();
                }, 300);
            });
        });

        // 加载用户数据
        function loadUsers(params = {}) {
            showLoading(true);
            
            const queryParams = new URLSearchParams(params).toString();
            const url = `/api/v1/users${queryParams ? '?' + queryParams : ''}`;
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        allUsers = data.data || [];
                        filteredUsers = [...allUsers];
                        renderUsers();
                        updateStatistics();
                    } else {
                        showMessage(data.message || '加载用户数据失败', 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('网络错误，请稍后重试', 'danger');
                })
                .finally(() => {
                    showLoading(false);
                });
        }

        // 筛选用户
        function filterUsers() {
            const searchTerm = document.getElementById('searchInput').value.trim().toLowerCase();
            const statusFilter = document.getElementById('statusFilter').value;
            const userTypeFilter = document.getElementById('userTypeFilter').value;

            if (searchTerm) {
                // 如果有搜索关键词，从服务器搜索
                loadUsers({ search: searchTerm });
                return;
            }

            // 否则进行本地筛选
            filteredUsers = allUsers.filter(user => {
                const statusMatch = !statusFilter || user.accountStatus === statusFilter;
                const typeMatch = !userTypeFilter || user.userType === userTypeFilter;
                return statusMatch && typeMatch;
            });

            renderUsers();
            updateStatistics();
        }

        // 搜索用户
        function searchUsers() {
            filterUsers();
        }

        // 清除筛选
        function clearFilters() {
            document.getElementById('searchInput').value = '';
            document.getElementById('statusFilter').value = '';
            document.getElementById('userTypeFilter').value = '';
            loadUsers();
        }

        // 刷新用户列表
        function refreshUsers() {
            clearFilters();
        }

        // 渲染用户表格
        function renderUsers() {
            const tbody = document.getElementById('usersTableBody');
            const emptyState = document.getElementById('emptyState');
            const tableContainer = document.getElementById('usersTableContainer');

            if (filteredUsers.length === 0) {
                tableContainer.style.display = 'none';
                emptyState.style.display = 'block';
                return;
            }

            tableContainer.style.display = 'block';
            emptyState.style.display = 'none';

            tbody.innerHTML = filteredUsers.map(user => `
                <tr>
                    <td><strong>${user.realName || '未设置'}</strong></td>
                    <td>${user.nickname || '未设置'}</td>
                    <td>
                        <span class="badge ${getUserTypeBadgeClass(user.userType)}">
                            ${getUserTypeText(user.userType)}
                        </span>
                    </td>
                    <td>
                        <span class="badge status-badge ${getStatusBadgeClass(user.accountStatus)}">
                            ${getStatusText(user.accountStatus)}
                        </span>
                    </td>
                    <td>
                        <span class="badge ${user.gender === 'MALE' ? 'bg-info' : 'bg-warning'}">
                            ${user.gender === 'MALE' ? '男' : '女'}
                        </span>
                    </td>
                    <td>${user.classId || '未分配'}</td>
                    <td>
                        <small class="text-muted">
                            ${formatDateTime(user.createdTime)}
                        </small>
                    </td>
                    <td>
                        <small class="text-muted">
                            ${formatDateTime(user.lastLoginTime)}
                        </small>
                    </td>
                    <td>
                        ${renderActionButtons(user)}
                    </td>
                </tr>
            `).join('');
        }

        // 渲染操作按钮
        function renderActionButtons(user) {
            let buttons = '';
            
            if (user.accountStatus === 'PENDING') {
                buttons = `
                    <div class="btn-group btn-group-sm" role="group">
                        <button type="button" class="btn btn-success btn-sm" 
                                onclick="approveUser(${user.id}, '${user.realName}')" 
                                title="批准用户">
                            <i class="bi bi-check-lg"></i>
                        </button>
                        <button type="button" class="btn btn-warning btn-sm" 
                                onclick="rejectUser(${user.id}, '${user.realName}')" 
                                title="拒绝用户">
                            <i class="bi bi-x-lg"></i>
                        </button>
                        <button type="button" class="btn btn-danger btn-sm" 
                                onclick="deleteUser(${user.id}, '${user.realName}')" 
                                title="删除用户">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                `;
            } else {
                buttons = `
                    <button type="button" class="btn btn-danger btn-sm" 
                            onclick="deleteUser(${user.id}, '${user.realName}')" 
                            title="删除用户">
                        <i class="bi bi-trash"></i>
                    </button>
                `;
            }
            
            return buttons;
        }

        // 更新统计信息
        function updateStatistics() {
            const total = allUsers.length;
            const pending = allUsers.filter(u => u.accountStatus === 'PENDING').length;
            const approved = allUsers.filter(u => u.accountStatus === 'APPROVED').length;
            const rejected = allUsers.filter(u => u.accountStatus === 'REJECTED').length;

            document.getElementById('totalUsersCount').textContent = total;
            document.getElementById('pendingUsersCount').textContent = pending;
            document.getElementById('approvedUsersCount').textContent = approved;
            document.getElementById('rejectedUsersCount').textContent = rejected;
        }

        // 显示加载状态
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const tableContainer = document.getElementById('usersTableContainer');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                tableContainer.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                tableContainer.style.display = 'block';
            }
        }

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageArea = document.getElementById('messageArea');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            
            messageArea.innerHTML = `
                <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                    <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // 自动隐藏成功消息
            if (type === 'success') {
                setTimeout(() => {
                    const alert = messageArea.querySelector('.alert');
                    if (alert) {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    }
                }, 3000);
            }
        }

        // 批准用户
        function approveUser(userId, userName) {
            pendingAction = 'approve';
            pendingUserId = userId;
            pendingUserName = userName;
            
            document.getElementById('modalTitle').textContent = '批准用户';
            document.getElementById('modalBody').innerHTML = `
                <p>确认要批准用户 <strong>"${userName}"</strong> 吗？</p>
                <p class="text-muted small">批准后，用户将能够正常使用系统功能。</p>
            `;
            document.getElementById('confirmBtn').className = 'btn btn-success';
            document.getElementById('confirmBtn').innerHTML = '<i class="bi bi-check-lg me-1"></i>批准';
            
            new bootstrap.Modal(document.getElementById('confirmModal')).show();
        }

        // 拒绝用户
        function rejectUser(userId, userName) {
            pendingAction = 'reject';
            pendingUserId = userId;
            pendingUserName = userName;
            
            document.getElementById('modalTitle').textContent = '拒绝用户';
            document.getElementById('modalBody').innerHTML = `
                <p>确认要拒绝用户 <strong>"${userName}"</strong> 吗？</p>
                <p class="text-muted small">拒绝后，用户将无法使用系统，需要重新提交审核。</p>
            `;
            document.getElementById('confirmBtn').className = 'btn btn-danger';
            document.getElementById('confirmBtn').innerHTML = '<i class="bi bi-x-lg me-1"></i>拒绝';
            
            new bootstrap.Modal(document.getElementById('confirmModal')).show();
        }

        // 删除用户
        function deleteUser(userId, userName) {
            pendingAction = 'delete';
            pendingUserId = userId;
            pendingUserName = userName;
            
            document.getElementById('modalTitle').textContent = '删除用户';
            document.getElementById('modalBody').innerHTML = `
                <div class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    <strong>警告：此操作不可逆！</strong>
                </div>
                <p>确认要删除用户 <strong>"${userName}"</strong> 吗？</p>
                <p class="text-danger small">
                    <i class="bi bi-info-circle me-1"></i>
                    删除用户将永久移除以下数据：
                </p>
                <ul class="small text-muted">
                    <li>用户基本信息</li>
                    <li>所有会话记录</li>
                    <li>所有练习记录</li>
                    <li>相关的音频文件</li>
                </ul>
            `;
            document.getElementById('confirmBtn').className = 'btn btn-danger';
            document.getElementById('confirmBtn').innerHTML = '<i class="bi bi-trash me-1"></i>确认删除';
            
            new bootstrap.Modal(document.getElementById('confirmModal')).show();
        }

        // 执行操作
        function executeAction() {
            if (!pendingAction || !pendingUserId) return;

            let url, method, body;
            
            if (pendingAction === 'delete') {
                // 删除操作使用DELETE方法
                url = `/api/v1/users/${pendingUserId}`;
                method = 'DELETE';
                body = null;
            } else {
                // 批准/拒绝操作使用POST方法
                url = `/api/v1/users/${pendingAction}`;
                method = 'POST';
                body = new FormData();
                body.append('userId', pendingUserId);
            }

            // 显示加载状态
            const confirmBtn = document.getElementById('confirmBtn');
            confirmBtn.disabled = true;
            confirmBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>处理中...';

            fetch(url, {
                method: method,
                body: body
            })
            .then(response => response.json())
            .then(data => {
                bootstrap.Modal.getInstance(document.getElementById('confirmModal')).hide();
                
                if (data.code === 0) {
                    let actionText;
                    switch(pendingAction) {
                        case 'approve': actionText = '批准'; break;
                        case 'reject': actionText = '拒绝'; break;
                        case 'delete': actionText = '删除'; break;
                        default: actionText = '操作';
                    }
                    showMessage(`用户 "${pendingUserName}" ${actionText}成功！`, 'success');
                    
                    // 刷新数据
                    setTimeout(() => {
                        loadUsers();
                    }, 1000);
                } else {
                    showMessage(data.message || '操作失败，请重试', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                bootstrap.Modal.getInstance(document.getElementById('confirmModal')).hide();
                showMessage('网络错误，请检查连接后重试', 'danger');
            })
            .finally(() => {
                // 重置状态
                confirmBtn.disabled = false;
                pendingAction = null;
                pendingUserId = null;
                pendingUserName = null;
            });
        }

        // 辅助函数
        function getUserTypeBadgeClass(userType) {
            switch(userType) {
                case 'STUDENT': return 'bg-primary';
                case 'TEACHER': return 'bg-success';
                case 'ADMIN': return 'bg-danger';
                default: return 'bg-secondary';
            }
        }

        function getUserTypeText(userType) {
            switch(userType) {
                case 'STUDENT': return '学生';
                case 'TEACHER': return '教师';
                case 'ADMIN': return '管理员';
                default: return '未知';
            }
        }

        function getStatusBadgeClass(status) {
            switch(status) {
                case 'PENDING': return 'bg-warning';
                case 'APPROVED': return 'bg-success';
                case 'REJECTED': return 'bg-danger';
                case 'INCOMPLETE': return 'bg-secondary';
                default: return 'bg-secondary';
            }
        }

        function getStatusText(status) {
            switch(status) {
                case 'PENDING': return '待审核';
                case 'APPROVED': return '已批准';
                case 'REJECTED': return '已拒绝';
                case 'INCOMPLETE': return '信息不完整';
                default: return '未知';
            }
        }

        function formatDateTime(dateTime) {
            if (!dateTime) return '未知';
            
            try {
                const date = new Date(dateTime);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (e) {
                return '无效日期';
            }
        }
    </script>
</body>
</html>